package cn.rubintry.weacar.autodingtalk

import android.R
import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import java.util.*


class AutoService() : Service() {

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        val notification = NotificationCompat.Builder(this, "AutoDingTalk")
            .setContentTitle("钉钉自动打卡程序")
            .setContentText("当前状态：运行中")
            .setSmallIcon(R.drawable.ic_lock_idle_alarm)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_lock_idle_alarm))

        val nm = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            nm.createNotificationChannel(
                NotificationChannel(
                    "AutoDingTalk",
                    "AutoDingTalk",
                    NotificationManager.IMPORTANCE_HIGH
                )
            )
        }
        startForeground(1, notification.build())


    }

    @SuppressLint("WrongConstant")
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val hour = intent?.getIntExtra("hour", 0)
        val minute = intent?.getIntExtra("minute", 0)

        val calendar: Calendar =  Calendar.getInstance()
        hour?.let {
            calendar.set(Calendar.HOUR_OF_DAY, it)
        }
        minute?.let {
            calendar.set(Calendar.MINUTE, it)
        }
        calendar.set(Calendar.SECOND, 0)

        val totalMillis : Long = (calendar.timeInMillis ?: 0) as Long

        val am = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager


        val intent = Intent(this, StartupReceiver::class.java)
        val pi = PendingIntent.getBroadcast(this, 0, intent, 0)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,  totalMillis, pi)
        }else{
            am.setExact(AlarmManager.RTC_WAKEUP,  totalMillis, pi)
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        val nm = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        nm.cancel(1)
    }
}